﻿using System.IO;
using UnityEngine;
using UnityEditor;
using JinndevEditor;

namespace Jinndev { 

    public class CreateModEditor : EditorWindow {

        [MenuItem(CommonEditorConst.EditorMenu + "/新建Mod")]
        public static void Open() {
            var window = GetWindow<CreateModEditor>("新建Mod");
            window.Show();
        }

        private string modName = "NewMod";
        private string description = "Description";
        private string author = "Author";

        private void OnGUI() {
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Mod名称", GUILayout.Width(50));
            modName = EditorGUILayout.TextField(modName, GUILayout.Width(500));
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Mod描述", GUILayout.Width(50));
            description = EditorGUILayout.TextArea(description, GUILayout.Width(500), GUILayout.Height(100));
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Mod作者", GUILayout.Width(50));
            author = EditorGUILayout.TextField(author, GUILayout.Width(500));
            EditorGUILayout.EndHorizontal();

            if (GUILayout.Button("创建", GUILayout.Width(200), GUILayout.Height(40))) {
                CreateMod();
            }
        }

        private void CreateMod() {
            if (string.IsNullOrWhiteSpace(modName)) {
                EditorUtility.DisplayDialog("Error", "Mod名称为空", "OK");
                return;
            }

            string rootDir = Path.Combine(Application.streamingAssetsPath, "Mod/" + modName);
            if (Directory.Exists(rootDir)) {
                EditorUtility.DisplayDialog("Error", "Mod名称已存在", "OK");
                return;
            }

            Directory.CreateDirectory(rootDir);
            Directory.CreateDirectory(Path.Combine(rootDir, "Config"));

            using (StreamWriter stream = File.CreateText(Path.Combine(rootDir, "Mod.json"))) {
                stream.WriteLine("{");
                stream.WriteLine($"	\"name\": \"{modName}\",");
                stream.WriteLine($"	\"description\": \"{description}\",");
                stream.WriteLine($"	\"author\": \"{author}\",");
                stream.WriteLine("	\"version\": \"1.0.0\",");
                stream.WriteLine("	\"supportGame\": \"1.0.0\"");
                stream.WriteLine("}");
            }

            AssetDatabase.Refresh();
            Debug.Log($"创建完成: {rootDir}");
        }

    }

}